<template>
  <div class="audit-echart component-root-container">
    <el-row class="date-picker-container">
      <el-date-picker id="monthPicker" ref="monthPicker" v-model="selectedMonth" type="month" format="yyyy-MM"
        value-format="yyyy-MM" @change="onMonthChanged" placeholder="请选择日期">
      </el-date-picker>
      <i type="primary" class="el-icon-caret-bottom" @click="toggleDatePicker"></i>
    </el-row>
    <el-main>
      <el-row>
        <el-col>
          <div class="chart-title">内存数据库数据服务调用趋势情况</div>
          <div class="chart-panel">
            <IEcharts style="min-height:320px;" :option="dbInvokeOptions" :loading="loading" :resizable="resizable" />
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="chart-title">三集中自动审核服务调用趋势</div>
          <div class="chart-panel">
            <IEcharts style="min-height:330px;" :option="auditInvokeOptions" :loading="loading" :resizable="resizable" />
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-title">调用次数最多的五个服务</div>
          <el-card class="chart-container">
            <el-table v-loading="logListLoading" ref="logTable" border :data="invokeTableData" class="table-bottom"
              element-loading-text="数据加载中...">
              <el-table-column prop="id" align="center" label="序号" width="50px">
              </el-table-column>
              <el-table-column prop="scene" align="center" label="场景名称" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="number" align="center" label="调用频率(次/月)" width="150px">
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

    </el-main>
  </div>
</template>

<script>
  import IEcharts from 'vue-echarts-v3/src/full.js'

  export default {
    components: {
      IEcharts
    },
    data() {
      return {
        selectedMonth: null,
        showDatePicker: true,
        listLoading: false,
        logListLoading: false,
        theLog: {
          scene: '',
          type: '',
          keyword: '',
          dateTime: []
        },
        dbInvokes: null,
        auditInvokes: null,
        tableData: null,
        usedTime: 0,
        logCounts: 0,

        paginationData: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        loading: false,
        resizable: true,
        desc: true,
        logCountsByTime: [],
        logDataByTime: []
      }
    },
    created() {
      this.setNowMonth()
      this.onMonthChanged()
    },
    mounted() {},
    computed: {
      dbInvokeOptions() {
        return this.dbInvokes
      },
      auditInvokeOptions() {
        return this.auditInvokes
      },
      invokeTableData() {
        return this.tableData
      }
    },
    methods: {
      async onMonthChanged() {
        this.dbInvokes = {}
        this.auditInvokes = {}
        this.dbInvokes = await this.loadDbInvokeData()
        this.auditInvokes = await this.loadAuditInvokeData()
        await this.loadTableData()
      },
      async setNowMonth() {
        var date = new Date()
        var seperator1 = '-'
        var year = date.getFullYear()
        var month = date.getMonth() + 1

        if (month >= 1 && month <= 9) {
          month = '0' + month
        }
        this.selectedMonth = year + seperator1 + month
      },
      async loadDbInvokeData() {
        var data = {
          'month': this.selectedMonth
        }
        const r = await this.$http({
          url: this.$http.adornBizUrl('/log/search/day/count'),
          method: 'post',
          data: this.$http.adornData('param=' + escape(JSON.stringify(data)), false),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        })
        let logs = r.data.data.data.sort((a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime())
        let xData = []
        let yData = []
        if (logs != null && logs.length > 0) {
          for (var i = 0; i < logs.length; i++) {
            xData.push(logs[i].createTime.substr(logs[i].createTime.length - 5, 5))
            yData.push(logs[i].count)
          }
        }
        return {
          toolbox: {
            show: true,
            right: 30,
            feature: {
              restore: {
                show: true
              },
              saveAsImage: {
                show: true
              },
              magicType: {
                show: true,
                type: ['bar', 'line']
              }
            }
          },
          xAxis: {
            type: 'category',
            name: '日期',
            data: xData
          },
          yAxis: {
            name: '次数',
            type: 'value'
          },
          grid: {
            top: '30px',
            left: '20px',
            right: '50px',
            bottom: '20px',
            containLabel: true
          },
          legend: {
            x: 'center',
            y: 'bottom',
            data: ['调用次数']
          },
          series: [{
            name: '调用次数',
            data: yData,
            type: 'bar',
            barMaxWidth: 30,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#666',
                    fontSize: 10
                  },
                  formatter: function(p) {
                    let value = ''
                    if (p.value > 0) {
                      value = p.value
                      if (value > 999) {
                        let parts = value.toString().split('.')
                        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                        value = parts.join('.')
                      }
                    }
                    return value
                  }
                }
              }
            }
          }],
          tooltip: {
            show: true, // 是否显示提示框，默认为true
            trigger: 'item', // 数据项图形触发
            axisPointer: { // 指示样式
              type: 'shadow',
              axis: 'auto'
            },
            padding: 5,
            textStyle: { // 提示框内容的样式
              color: '#fff'
            }
          }
        }
        // return r.data
      },
      async loadAuditInvokeData() {
        var data = {
          'month': this.selectedMonth,
          'scene': ['2.7']
        }
        const r = await this.$http({
          url: this.$http.adornBizUrl('/log/search/day/count'),
          method: 'post',
          data: this.$http.adornData('param=' + escape(JSON.stringify(data)), false),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        })
        //console.log(r)
        let logs = r.data.data.data
        let xData = []
        let yData = []
        if (logs != null && logs.length > 0) {
          for (var i = 0; i < logs.length; i++) {
            xData.push(logs[i].createTime.substr(logs[i].createTime.length - 5, 5))
            yData.push(logs[i].count)
          }
        }
        return {
          toolbox: {
            show: true,
            right: 30,
            feature: {
              restore: {},
              saveAsImage: {},
              magicType: {
                show: true,
                type: ['bar', 'line']
              }
            }
          },
          xAxis: {
            type: 'category',
            name: '日期',
            data: xData
          },
          yAxis: {
            name: '次数',
            type: 'value'
          },
          series: [{
            name: '调用次数',
            data: yData,
            type: 'bar',
            barMaxWidth: 30,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#666',
                    fontSize: 10
                  },
                  formatter: function(p) {
                    let value = '';
                    if (p.value > 0) {
                      value = p.value;
                      if (value > 999) {
                        let parts = value.toString().split('.');
                        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                        value = parts.join('.');
                      }
                    }
                    return value;
                  }
                }
              }
            }
          }],
          legend: {
            x: 'center',
            y: 'bottom',
            data: ['调用次数']
          },
          grid: {
            top: '30px',
            left: '20px',
            right: '50px',
            bottom: '20px',
            containLabel: true
          },
          tooltip: {
            show: true, // 是否显示提示框，默认为true
            trigger: 'item', // 数据项图形触发
            axisPointer: { // 指示样式
              type: 'shadow',
              axis: 'auto'
            },
            padding: 5,
            textStyle: { // 提示框内容的样式
              color: '#fff'
            }
          }
        }
        // return r.data
      },
      async loadTableData() {
        const data = {
          'month': this.selectedMonth,
          'limit': 5
        }
        const r = await this.$http({
          url: this.$http.adornBizUrl('/log/search/scene/count'),
          method: 'post',
          data: this.$http.adornData('param=' + escape(JSON.stringify(data)), false),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        })

        if (r.data.data.data) {
          var most5Invoke = r.data.data.data.sort((a, b) => b.count - a.count)
          this.tableData = []
          for (let i = 0; i < most5Invoke.length && i < 5; i++) {
            let invokeInfo = {}
            invokeInfo.id = i + 1
            invokeInfo.scene = most5Invoke[i].scene
            invokeInfo.number = this.numFormatter(most5Invoke[i].count)
            this.tableData.push(invokeInfo)
          }
          //console.log(this.tableData)
        }
        return null
      },
      setDefaultTime() {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        this.theLog.dateTime = [start, end]
        this.getLogChart(this.dateFormat(start), this.dateFormat(end))
      },
      dateFormat(date) {
        const timeDate = new Date(date)
        const timeDateString = timeDate.toJSON()
        return timeDateString.replace('T', ' ').slice(0, 19)
      },
      numFormatter(num) {
        let value = ''
        if (num > 0) {
          value = num
          if (value > 999) {
            let parts = value.toString().split('.')
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
            value = parts.join('.')
          }
        }
        return value
      },
      toggleDatePicker() {
        this.$refs.monthPicker.focus()
      },
      // 分页跳转
      currentChange(targetPage) {
        this.paginationData['currentPage'] = targetPage
        // table数据接口
        this.buttonClick()
      },
      // 分页跳转
      handleSizeChange(size) {
        this.paginationData['pageSize'] = size
        this.paginationData['currentPage'] = 1
        // table数据接口
        this.buttonClick()
      },
      async getLogChart() {
        const r = await this.$http({
          // url: this.$http.adornBizUrl('/log/search/count'),
          url: this.$http.adornBizUrl('/audit/dbSrvInvokeTrend'),
          method: 'get',
          data: this.$http.adornData('param=' + JSON.stringify(this.selectedMonth), false),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        })
        if (r.data.data.data) {
          for (var log in r.data.data.data) {
            this.logCountsByTime.push(new Date(log.day))
            this.logDataByTime.push(log.number)
          }
          // this.logCountsByTime = r.data.data.data.sort((a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime())
        }
      },
      async buttonClick() {
        this.listLoading = true
        try {
          await this.$refs['theLogRule'].validate()
          const startTime = new Date()
          const data = {
            type: this.theLog['type'],
            scene: [this.theLog['scene']],
            startTime: this.dateFormat(this.theLog['dateTime'][0]),
            endTime: this.dateFormat(this.theLog['dateTime'][1]),
            limit: this.paginationData.pageSize,
            page: this.paginationData.currentPage,
            desc: this.desc
          }
          this.getLogChart(data.startTime, data.endTime, data.scene, data.type)
          this.logListLoading = true
          const r = await this.$http({
            url: this.$http.adornBizUrl('/log/search/data'),
            method: 'post',
            data: this.$http.adornData('param=' + JSON.stringify(data), false),
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
          })
          if (r.data.data) {
            const endTime = new Date()
            this.usedTime = Math.round(endTime.getTime() - startTime.getTime()) / 1000
            this.logListLoading = false
            this.logDataByTime = r.data.data.data
            this.paginationData.total = this.logDataByTime.length
            this.logCounts = r.data.data.data.length
          }
        } catch (e) {
          console.log(e)
        } finally {
          this.listLoading = false
        }
      }
    }
  }
</script>

<style lang="scss">
  .audit-echart {
    .date-picker-container {
      display: flex;
      justify-content: center;
      align-items: flex-end;

      .el-icon-caret-bottom {
        font-size: 30px;
        color: red;
      }
    }

    .chart-title {
      font-weight: 800;
      line-height: 35px;
    }

    .chart-panel {
      border: 1px solid #ebeef5;
      background-color: #fff;
      color: #303133;
      border-radius: 4px;
      padding: 10px 5px;
      overflow: hidden;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
    }

    .el-card.is-always-shadow {
      border: 1px solid #e8e6e6;
      height: 350px;
    }
  }
</style>
